/*
 * Created on Mar 7, 2005
 */
package org.scohen.juploadr.prefs;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.scohen.juploadr.Messages;

public class ConnectionForm extends BaseConfigurationForm {

    private static final Configuration config = Configuration.getInstance();
    private Button useProxy;
    private Text host;
    private Text port;
    private Text username;
    private Text password;
    private Button throttleBandwidth;
    private Text throttleKPerSecond;
    private Label throttleKPerSecondLabel;
    private Label hostLabel;
    private Label portLabel;
    private Label usernameLabel;
    private Label passwordLabel;

    private Group proxyGroup;
    private Group throttleGroup;

    public ConnectionForm(Composite parent) {
        super(parent);
    }

    /**
     * 
     */
    protected void initUI() {
        GridLayout layout = new GridLayout();
        GridData data = new GridData(GridData.FILL_HORIZONTAL);
        initBandwidthThrottlingUI();

        useProxy = new Button(this, SWT.CHECK);
        useProxy.setText(Messages.getString("juploadr.ui.label.enable.proxy")); //$NON-NLS-1$
        useProxy.setSelection(config.isProxyEnabled());
        useProxy.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
                ConnectionForm.this.proxyButtonClicked();
			}
		});

        proxyGroup = new Group(this, SWT.SHADOW_NONE);
        layout = new GridLayout();
        layout.numColumns = 2;
        layout.verticalSpacing = 5;
        proxyGroup.setLayout(layout);

        proxyGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        proxyGroup.setText(Messages
                .getString("juploadr.ui.label.proxy.settings")); //$NON-NLS-1$
        proxyGroup.setEnabled(useProxy.getSelection());

        hostLabel = new Label(proxyGroup, 0);
        hostLabel.setText(Messages.getString("juploadr.ui.label.proxy.host")); //$NON-NLS-1$
        this.host = new Text(proxyGroup, SWT.BORDER);
        this.host.setText(config.getProxyHost());
        host.setLayoutData(data);

        portLabel = new Label(proxyGroup, 0);
        portLabel.setText(Messages.getString("juploadr.ui.label.proxy.port")); //$NON-NLS-1$
        this.port = new Text(proxyGroup, SWT.BORDER);
        this.port.setText(String.valueOf(config.getProxyPort()));
        GC gc = new GC(proxyGroup);
        GridData portData = new GridData();
        portData.widthHint = gc.textExtent("0000").x; //$NON-NLS-1$
        port.setLayoutData(portData);
        gc.dispose();
        // Don't let the user enter anything other than integers.
        this.port.addVerifyListener(new VerifyListener() {
            public void verifyText(VerifyEvent e) {
                if (e.text.length() > 0) {
                    try {
                        Integer.parseInt(e.text);
                    } catch (NumberFormatException nfe) {
                        e.doit = false;
                    }
                }
            }
        });

        usernameLabel = new Label(proxyGroup, SWT.NONE);
        usernameLabel.setText(Messages
                .getString("juploadr.ui.label.proxy.username")); //$NON-NLS-1$
        this.username = new Text(proxyGroup, SWT.BORDER);
        this.username.setText(config.getProxyUsername());
        data = new GridData(GridData.FILL_HORIZONTAL);
        this.username.setLayoutData(data);
        passwordLabel = new Label(proxyGroup, SWT.NONE);
        passwordLabel.setText(Messages
                .getString("juploadr.ui.label.proxy.password")); //$NON-NLS-1$
        this.password = new Text(proxyGroup, SWT.BORDER | SWT.PASSWORD);
        this.password.setText(config.getProxyPassword());
        data = new GridData(GridData.FILL_HORIZONTAL);
        this.password.setLayoutData(data);
        // For now, an ugly but functional vertical stack.
        layout = new GridLayout();
        layout.numColumns = 1;
        this.setLayout(layout);
        this.addDisposeListener(new DisposeListener() {
            public void widgetDisposed(DisposeEvent event) {
                ConnectionForm.this.disposed(event);
            }
        });

        setFieldsEnabled(config.isProxyEnabled());
        setThrottlingFieldsEnabled(config.isThrottlingEnabled());
    }

    /**
     * @param layout
     */
    private void initBandwidthThrottlingUI() {

        throttleBandwidth = new Button(this, SWT.CHECK);
        throttleBandwidth.setText(Messages
                .getString("juploadr.ui.connection.label.throttle-upstream")); //$NON-NLS-1$
        throttleBandwidth.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
                ConnectionForm.this.throttleButtonClicked();
			}
		
		});
        throttleGroup = new Group(this, SWT.SHADOW_NONE);
        throttleGroup.setText(Messages
                .getString("juploadr.ui.connection.label.throttling.settings")); //$NON-NLS-1$

        GridLayout layout = new GridLayout();
        layout.numColumns = 2;
        layout.verticalSpacing = 5;
        throttleGroup.setLayout(layout);
        throttleGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        throttleKPerSecondLabel = new Label(throttleGroup, 0);
        throttleKPerSecondLabel.setText(Messages
                .getString("juploadr.ui.connection.label.maxupload")); //$NON-NLS-1$
        throttleKPerSecond = new Text(throttleGroup, SWT.BORDER);
        throttleKPerSecond
                .setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        if (config.isThrottlingEnabled()) {
            throttleKPerSecond.setText(Integer.toString(config
                    .getMaxKPerSecond() / 1024, 10));

        }

        throttleKPerSecond.addVerifyListener(new VerifyListener() {
            public void verifyText(VerifyEvent event) {
                if (event.text.length() > 0) {
                    String input = ((Text) event.widget).getText() + event.text;
                    try {
                        int kbps = Integer.parseInt(input);
                        if (kbps <= 0) {
                            event.doit = false;
                        }
                    } catch (NumberFormatException nfe) {
                        event.doit = false;
                    }
                }
            }
        });

    }

    protected void throttleButtonClicked() {
        setThrottlingFieldsEnabled(throttleBandwidth.getSelection());
        this.redraw();
    }

    private void setThrottlingFieldsEnabled(boolean enabled) {
        throttleBandwidth.setSelection(enabled);
        throttleKPerSecond.setEnabled(enabled);
        throttleKPerSecondLabel.setEnabled(enabled);
        throttleGroup.setEnabled(enabled);
    }

    /**
     * @param b
     */
    private void setFieldsEnabled(boolean enabled) {
        proxyGroup.setEnabled(enabled);
        host.setEnabled(enabled);
        hostLabel.setEnabled(enabled);
        port.setEnabled(enabled);
        portLabel.setEnabled(enabled);
        username.setEnabled(enabled);
        usernameLabel.setEnabled(enabled);
        password.setEnabled(enabled);
        passwordLabel.setEnabled(enabled);
        this.redraw();
    }

    private void proxyButtonClicked() {
        setFieldsEnabled(useProxy.getSelection());
    }

    public void saveChanges() {
        config.setThrottlingEnabled(throttleBandwidth.getSelection());
        if (throttleBandwidth.getSelection()) {
            config.setMaxKPerSecond(Integer.parseInt(throttleKPerSecond
                    .getText()) * 1024);
        }

        if (useProxy.getSelection()) {
            config.setProxyEnabled(true);
            config.setProxyHost(this.host.getText());
            String portNum = this.port.getText();
            config.setProxyPort((portNum.length() > 0) ? Integer
                    .parseInt(portNum) : Configuration.DEFAULT_PROXY_PORT);
            config.setProxyUsername(this.username.getText());
            config.setProxyPassword(this.password.getText());
        } else {
            config.setProxyEnabled(false);
            // config.setProxyHost(null);
            // config.setProxyPort(0);
            // config.setProxyUsername(null);
            // config.setProxyPassword(null);
        }
    }

    public Fault validateChanges() {
        return null;
    }

    public String getFormName() {
        return Messages.getString("juploadr.ui.proxy.form.title"); //$NON-NLS-1$
    }

    public void disposed(DisposeEvent event) {
        useProxy.dispose();
        proxyGroup.dispose();
        host.dispose();
        port.dispose();
        username.dispose();
        password.dispose();
        hostLabel.dispose();
        portLabel.dispose();
        usernameLabel.dispose();
        passwordLabel.dispose();
        throttleBandwidth.dispose();
        throttleKPerSecond.dispose();
        throttleKPerSecondLabel.dispose();
        throttleGroup.dispose();
    }
}